package com.hykj.coca.control;


import com.github.pagehelper.PageInfo;
import com.hykj.coca.model.MeassgeModel;
import com.hykj.coca.model.MeassgeUserModel;
import com.hykj.coca.model.UserModel;
import com.hykj.coca.result.AppBack;
import com.hykj.coca.service.*;
import com.hykj.coca.utils.StringUtil;
import com.hykj.coca.utils.TokenUtil;
import io.swagger.annotations.Api;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "APP接口")
@RestController
@EnableAutoConfiguration
@RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/api", produces = "application/json; charset=utf-8")
public class MoblieApi {

    private Logger logger = Logger.getLogger(MoblieApi.class);

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MeassgeClassService meassgeClassService;

    @Autowired
    private MeassgeService meassgeService;

    @Autowired
    private MeassgeUserService meassgeUserService;

    /**
     * 获取该用户消息列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/op=GetMsgList")
    public HashMap GetMsgList(@RequestParam String userId,
                              @RequestParam Integer page,
                              @RequestParam Integer pageSize) {
        HashMap condition = new HashMap();
        condition.put("user_id", userId);
        Integer allCount = meassgeService.getUnReadCount(condition);
//        condition.put("is_read", "0");
        condition.put("change", 1);
        PageInfo p = meassgeService.getList(condition, page, pageSize);
        Integer count = meassgeService.getUnReadCount(condition);
        HashMap countBack = new HashMap();
        countBack.put("totalCount", allCount);
        countBack.put("noReadCount", count);
        countBack.put("status", 0);

        if (p.isHasNextPage()) {
            countBack.put("hasNext", 1);

        } else {
            countBack.put("hasNext", 0);
        }
        countBack.put("result", p.getList());
        return countBack;
    }

    /**
     * 读取信息
     *
     * @param userId
     * @param msgId
     * @return
     */

    @RequestMapping(value = "/op=ReadMsg")
    public AppBack ReadMsg(@RequestParam String userId,
                           @RequestParam Integer msgId) {
        HashMap condition = new HashMap();
        condition.put("user_id", userId);
        condition.put("meassge_id", msgId);
        MeassgeModel meassgeModel=meassgeService.getById(msgId);
        if (meassgeModel==null){
            return new AppBack(-1, "信息不存在");
        }
        List<MeassgeUserModel> meassgeUserModels = meassgeUserService.getList(condition);
        if (meassgeUserModels.size() == 0) {
            return new AppBack(-1, "信息不存在");
        }
        MeassgeUserModel meassgeUserModel = meassgeUserModels.get(0);
        meassgeUserModel.setIs_read(1);
        meassgeUserService.update(meassgeUserModel);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String createTime = dateFormat.format(meassgeModel.getCreate_time());
        HashMap backMap = new HashMap();
        backMap.put("msgTitle", meassgeModel.getTitle());
        backMap.put("msgContent", meassgeModel.getMeassge_content());
        backMap.put("createTime", createTime);
        return new AppBack(backMap);
    }

    /**
     * 登录
     *
     * @param phone
     * @param pass
     * @return
     */
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/op=UserLogin")
    public AppBack UserLogin(@RequestParam String phone,
                             @RequestParam String pass) {
        if (StringUtil.isEmptyString(phone)) {
            return new AppBack(-1, "必填信息不能为空");
        }
        if (StringUtil.isEmptyString(pass)) {
            return new AppBack(-1, "必填信息不能为空");
        }
        AppBack<Map> appBack = userService.MobileLogin(phone, pass);
        return appBack;
    }

    /**
     * 绑定太古帐号
     *
     * @param phone
     * @param pass
     * @return
     */
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/op=BindTaiGu")
    public AppBack BindTaiGu(
                             @RequestParam String phone,
                             @RequestParam(required = false) String pass) {
        if (StringUtil.isEmptyString(phone)) {
            return new AppBack(-1, "必填信息不能为空");
        }

        HashMap condition = new HashMap();
        condition.put("phone", phone);
        UserModel userModelCheck = userService.nameCheck(condition);
        HashMap backMap = new HashMap();
        if (userModelCheck != null) {
            backMap.put("phone", userModelCheck.getPhone());
            backMap.put("token", userModelCheck.getToken());
            backMap.put("userId", userModelCheck.getId());
        } else {
            UserModel userModel = new UserModel();
            userModel.setPhone(phone);

            if (StringUtil.isEmptyString(pass)) {
                userModel.setPassword("123456");
            } else {
                userModel.setPassword(pass);
            }
            String token = TokenUtil.getInstance().generateTokenUUID();
            userModel.setStatus(1);
            userModel.setToken(token);
            userService.create(userModel);
            backMap.put("userId", userModel.getId());
            backMap.put("phone", userModel.getPhone());
            backMap.put("token", token);
        }
        return new AppBack(backMap);

    }

    /**
     * 微信登录
     *
     * @param openId
     * @return
     */
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/op=WXLogin")
    @ResponseBody
    public AppBack WXLogin(@RequestParam String openId
//            ,@RequestParam String access_token
    ) {

//        String resultx;
//        try {
//            resultx = Util.getURLByPost("https://api.weixin.qq.com/sns/userinfo", "openid=" + openId + "&access_token=" + access_token);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new AppBack(-1, "连接微信失败");
//        }
//        logger.info(resultx);
//        Map map = JSON.parseObject(resultx, Map.class);
//        if (map.get("openid") == null) {
//            return new AppBack(-1, "微信验证失败");
//        }
        Map conditon = new HashMap();
        conditon.put("wx_open_id", openId);
        List<UserModel> userModels = userService.getList(conditon);
        if (userModels.size() == 0) {//有账号先注册
            return new AppBack(1, "跳转页面,请绑定帐号信息");
        }
        UserModel userModel = userModels.get(0);
        HashMap backMap = new HashMap();
        backMap.put("userId", userModel.getId());
        backMap.put("phone", userModel.getPhone());
        backMap.put("token", userModel.getToken());
        return new AppBack(backMap);
    }

    /**
     * 绑带微信账户
     *
     * @param phone
     * @param openId
     * @param password
     * @return
     */
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/op=BindWxPhone")
    public AppBack BindWxPhone(@RequestParam String phone,
                               @RequestParam String openId,
                               @RequestParam(required = false) String password) {
        if (StringUtil.isEmptyString(phone)) {
            return new AppBack(-1, "必填信息不能为空");
        }

        if (StringUtil.isEmptyString(openId)) {
            return new AppBack(-1, "必填信息不能为空");
        }

        HashMap condition = new HashMap();
        condition.put("phone", phone);
        UserModel userModelCheck = userService.nameCheck(condition);
        HashMap backMap = new HashMap();
        if (userModelCheck != null) {
            userModelCheck.setWx_open_id(openId);
            userService.update(userModelCheck);
            backMap.put("msg", "绑定原有账户");
            backMap.put("phone", userModelCheck.getPhone());
            backMap.put("token", userModelCheck.getToken());
            backMap.put("userId", userModelCheck.getId());
//            return  new AppBack(-1,"账户已经被注册");

        } else {
            UserModel userModel = new UserModel();
            userModel.setPhone(phone);
            if (StringUtil.isEmptyString(password)) {
                userModel.setPassword("123456");
            } else {
                userModel.setPassword(password);
            }
            String token = TokenUtil.getInstance().generateTokenUUID();
            userModel.setWx_open_id(openId);
            userModel.setStatus(1);
            userModel.setToken(token);
            userService.create(userModel);
            backMap.put("msg", "创建新账户");
            backMap.put("userId", userModel.getId());
            backMap.put("phone", userModel.getPhone());
            backMap.put("token", token);
        }
        return new AppBack(backMap);

    }
}
